<template>
  <div>
   <!-- 面包屑导航 -->
   <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
   </el-breadcrumb>
   <!-- 卡片视图 -->
   <el-card>
      <el-row>
         <el-col>
            <el-button type='primary'>添加角色</el-button>
         </el-col>
      </el-row>
      <!-- 角色列表区 -->
      <el-table :data="roleList" border stripe>
         <el-table-column type="expand">
            <template slot-scope="scope">
               <el-row v-for="(item1,i1) in scope.row.children" :key="item1.id" :class="['bd-bottom', 'vcenter', i1 === 0 ? 'bd-top':'']">
                  <el-col :span="5">
                     <!-- 一级权限 -->
                     <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                     <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="19">
                     <!-- 二级&三级权限 -->
                     <el-row v-for="(item2,i2) in item1.children" :key="i2" :class="['vcenter', i2 === 0 ? '':'bd-top']">
                        <!-- 嵌套渲染二级权限 -->
                        <el-col :span="6">
                           <el-tag closable @close="removeRightById(scope.row,item2.id)" type="success">{{item2.authName}}</el-tag>
                           <i class="el-icon-caret-right"></i>
                        </el-col>
                        <el-col :span="18">
                              <el-tag
                              type="warning"
                              v-for="(item3,i3) in item2.children"
                              :key="i3"
                              closable
                              @close="removeRightById(scope.row,item3.id)">
                              {{item3.authName}}
                              </el-tag>
                        </el-col>
                     </el-row>
                  </el-col>
               </el-row>
            </template>
         </el-table-column>
         <el-table-column type="index" label="#"></el-table-column>
         <el-table-column label="角色名称" prop="roleName"></el-table-column>
         <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
         <el-table-column label="操作" prop="level" width="300px">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" size='mini'>编辑</el-button>
              <el-button type="danger" icon="el-icon-delete" size='mini'>删除</el-button>
              <el-button type="warning" icon="el-icon-setting" size='mini' @click="showSetRightDialog(scope.row)">分配权限</el-button>
            </template>
         </el-table-column>
      </el-table>
   </el-card>

   <!-- 分配权限对话框 -->
  <el-dialog
   title="分配权限"
   :visible.sync="setRightdialogVisible"
   width="50%"
   @close="showSetRightDialogClosed">
   <!-- 树形控件 -->
  <el-tree
  :data="rightsList"
  :props="treeProps"
  show-checkbox
  node-key='id'
  default-expand-all
  :default-checked-keys='defKeys'
  ref="treeRef"></el-tree>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRightdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights" >确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  name: 'roles',
  data() {
    return {
      // 所有角色列表
      roleList: [],
      // 权限对话框的显示隐藏
      setRightdialogVisible: false,
      // 所有权限数据
      rightsList: [],
      // 树形控件绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点id值
      defKeys: [],
      // 选中的用户id
      roleId: ''
    }
  },
  methods: {
    getRolesList() {
      this.$http.get('roles').then(res => {
        let result = res.data
        if (result.meta.status !== 200) return this.$message.error('获取角色列表失败')
        this.roleList = result.data
      })
    },
    // 根据id删除权限
    removeRightById(role, rightId) {
      // 弹框提醒
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`roles/${role.id}/rights/${rightId}`).then(res => {
          let result = res.data
          if (result.meta.status !== 200) return this.$message.error('删除权限失败')
          role.children = result.data
          this.$message.success('删除成功')
        })
      }).catch(() => {
        this.$message.success('删除取消')
      });
    },
    // 权限分配对话框展示
    showSetRightDialog(role) {
      this.roleId = role.id
      // 获取所有权限数据，树形图获取
      this.$http.get('rights/tree').then(res => {
        let result = res.data
        if (result.meta.data) return this.$message.error('获取权限列表失败')
        this.rightsList = result.data
        // 获取三级权限id
        this.getLeafKeys(role, this.defKeys)
        this.setRightdialogVisible = true
      })
    },
    // 监听分配权限对话框的关闭
    showSetRightDialogClosed() {
      this.defKeys = []
    },
    // 递归形式获取角色下三级权限id
    getLeafKeys(node, arr) {
      if (!node.children) {
      // 如果不包含children，就是三级节点
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 分配角色权限
    allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      console.log(keys)
      const idStr = keys.join(',')
      this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
        .then(res => {
          let result = res.data
          if (result.meta.status !== 200) return this.$message.error('权限更改失败')
          this.getRolesList()
          this.setRightdialogVisible = false
        })
    }
  },
  created() {
    this.getRolesList()
  },
}
</script>

<style lang="stylus" scoped>
.el-tag
   margin 7px
.bd-top
   border-top 1px solid #eee
.bd-bottom
   border-bottom 1px solid #eee
.vcenter
   display flex
   align-items center
</style>
